import React, { useState, useEffect } from 'react';
import { Category } from '../types';

const App: React.FC = () => {
  const [customCategories, setCustomCategories] = useState<Category[]>([]);
  const [newCategoryName, setNewCategoryName] = useState<string>('');
  const [apiKey, setApiKey] = useState<string>('');
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle');

  // 从 chrome.storage 加载自定义分类和API密钥
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const result = await chrome.storage.local.get(['customCategories', 'cursorApiKey']);
        if (result.customCategories) {
          setCustomCategories(result.customCategories);
        }
        if (result.cursorApiKey) {
          setApiKey(result.cursorApiKey);
        }
      } catch (err) {
        console.error('加载设置失败:', err);
      }
    };

    loadSettings();
  }, []);

  // 保存设置到 chrome.storage
  const saveSettings = async () => {
    try {
      setIsSaving(true);
      await chrome.storage.local.set({ 
        customCategories,
        cursorApiKey: apiKey 
      });
      setSaveStatus('success');
      setTimeout(() => setSaveStatus('idle'), 3000);
    } catch (err) {
      console.error('保存设置失败:', err);
      setSaveStatus('error');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddCategory = () => {
    if (newCategoryName.trim() === '') return;
    
    const newCategory: Category = {
      id: Date.now().toString(),
      name: newCategoryName.trim(),
      isCustom: true
    };
    
    setCustomCategories([...customCategories, newCategory]);
    setNewCategoryName('');
  };

  const handleRemoveCategory = (id: string) => {
    setCustomCategories(customCategories.filter(category => category.id !== id));
  };

  return (
    <div className="container mx-auto p-6 max-w-2xl">
      <h1 className="text-2xl font-bold mb-6">BookmarkVision 设置</h1>
      
      {/* API设置部分 */}
      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">Cursor API 设置</h2>
        <p className="text-gray-600 mb-4">
          设置Cursor API密钥以启用智能书签分类功能。
        </p>
        
        <div className="mb-4">
          <label className="block text-gray-700 mb-2" htmlFor="apiKey">
            API密钥
          </label>
          <input
            id="apiKey"
            type="password"
            className="w-full border border-gray-300 rounded px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary"
            placeholder="输入Cursor API密钥"
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
          />
          <p className="text-sm text-gray-500 mt-1">
            如果没有API密钥，将使用基础规则进行分类。
          </p>
        </div>
      </div>
      
      {/* 自定义分类部分 */}
      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">自定义分类</h2>
        <p className="text-gray-600 mb-4">
          创建您自己的书签分类来组织和过滤书签。
        </p>
        
        <div className="mb-6">
          <div className="flex mb-4">
            <input
              type="text"
              className="flex-1 border border-gray-300 rounded-l px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="输入新分类名称"
              value={newCategoryName}
              onChange={(e) => setNewCategoryName(e.target.value)}
            />
            <button
              className="bg-primary text-white rounded-r px-4 py-2 hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-primary"
              onClick={handleAddCategory}
            >
              添加
            </button>
          </div>
          
          <ul className="space-y-2">
            {customCategories.map((category) => (
              <li
                key={category.id}
                className="flex items-center justify-between border border-gray-200 rounded p-3"
              >
                <span>{category.name}</span>
                <button
                  className="text-red-500 hover:text-red-700"
                  onClick={() => handleRemoveCategory(category.id)}
                >
                  删除
                </button>
              </li>
            ))}
            {customCategories.length === 0 && (
              <li className="text-gray-500 text-center py-4">
                尚未添加自定义分类
              </li>
            )}
          </ul>
        </div>
        
        <div className="flex justify-end">
          <button
            className={`px-4 py-2 rounded font-medium ${
              isSaving
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-primary text-white hover:bg-primary-dark'
            }`}
            onClick={saveSettings}
            disabled={isSaving}
          >
            {isSaving ? '保存中...' : '保存设置'}
          </button>
        </div>
        
        {saveStatus === 'success' && (
          <div className="mt-4 p-2 bg-green-100 text-green-700 rounded">
            设置已保存
          </div>
        )}
        
        {saveStatus === 'error' && (
          <div className="mt-4 p-2 bg-red-100 text-red-700 rounded">
            保存失败，请重试
          </div>
        )}
      </div>
    </div>
  );
};

export default App; 